<?php
/**
 * Router class
 *
 * @author dmitry y.
 * 
 * 
 */

class Access_Router {
    private $registry ;
    private $path ;
    private $args = array() ;
    private $id ;

    //init
    function __construct($registry) 
    {
            $this->registry = $registry ;
    }
    
    function setPath($path) 
    {
        $path = trim($path, '/\\') ;
        $path .= DIR;
        if (!is_dir($path)) {
                throw new Exception ('Invalid controller path: `' . $path . '`');
        }
        $this->path = $path;
    }
    
    private function getController(&$file, &$controller, &$action, &$args) 
    {
        $route = (empty($_GET['route'])) ? '' : $_GET['route'];
        if (empty($route)) { $route = 'index'; }
        // get parts
        $route = trim($route, '/\\');
        $parts = explode('/', $route);
        $countParts = count($parts) ;
        if ($countParts > 2) {
            $this->id = $parts[2] ;
            for ($i=2; $i<=$countParts; $i++){
                unset ($parts[$i]) ;
            }
        }
        // finding controller
        $cmdPath = $this->path;
        foreach ($parts as $part) {
                $fullPath = $cmdPath . $part;
                // finding dir
                if (is_dir($fullPath)) {
                        $cmdPath .= $part . DIR;
                        array_shift($parts);
                        continue;
                }
                // finding file
                if (is_file($fullPath . '.php')) {
                        $controller = $part;
                        array_shift($parts);
                        break;
                }
        }
        if (empty($controller)) { $controller = 'index'; };
        // get action
        $action = array_shift($parts);
        if (empty($action)) { $action = 'index'; }
        $file = 'app/controller/' . $controller . '.php' ;
        $args = $parts;
    }
    
    function delegate() {
        // path
        $this->getController($file, $controller, $action, $args);
        // file accesseble?
        if (!is_readable($file)) {
                die ('404 Not Found');
        }
        // include file
        require_once $file;
        // make controller
        $class = 'controller_'.$controller;
        $_SESSION['controller'] = $controller;
        $controller = new $class($this->registry);
        // action is accessible
        if (!is_callable(array($controller, $action))) {
                die ('<h3>' . $action . ' 404 Not Found </h3>');
        }
        // make action
        $controller->$action($this->id);
        $_SESSION['action'] = $action;
        $_SESSION['article'] = $this->id;
    }
}